package top.lucky.zookeeper.utils;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

/**
 * @author Jane
 * @date 2022/12/5, 12:30
 */
@Component
public class ZkClient {
	private ZooKeeper zooKeeper;
	
	@PostConstruct
	public void init() {
		//获取连接 项目启动时
		CountDownLatch countDownLatch = new CountDownLatch(1);
		try {
			zooKeeper = new ZooKeeper("192.168.0.113:2181", 30000, new Watcher() {
				@Override
				public void process(WatchedEvent watchedEvent) {
					Event.KeeperState state = watchedEvent.getState();
					if (state.equals(Event.KeeperState.SyncConnected) && watchedEvent.getType().equals(Event.EventType.None)) {
						System.out.println("获取连接... " + state);
						countDownLatch.countDown();
					} else if (Event.KeeperState.Closed.equals(state)) {
						System.out.println("关闭连接... ");
					}
				}
			});
			countDownLatch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@PreDestroy
	public void destroy() {
		//项目停止前 销毁连接
		try {
			if (zooKeeper != null) {
				zooKeeper.close();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
